// 引入three.js
import * as THREE from 'three';
import {countryLine} from './line.js'
import config from './config.js'

import { OBJLoader } from '../../../node_modules/three/examples/jsm/loaders/OBJLoader.js'
import * as TWEEN  from '../../../node_modules/three/examples/jsm/libs/tween.module.js'

import { xyz2xyz } from './math.js'

var R = config.R;//地球半径
var earth = new THREE.Group();//地球组对象
//earth.add(createSphereMesh(R));//球体Mesh插入earthGroup中
// R * 1.001比地球R稍大，以免深度冲突
earth.add(countryLine(R * 1.001));//国家边界集合插入earthGroup中

// r：地球半径
function createSphereMesh(r) {
  // TextureLoader创建一个纹理加载器对象，可以加载图片作为纹理贴图
  var textureLoader = new THREE.TextureLoader();
  var texture = textureLoader.load('./earthmap1k.jpg');//加载纹理贴图
  var geometry = new THREE.SphereGeometry(r, 40, 40); //创建一个球体几何对象
  //材质对象Material
  // MeshLambertMaterial  MeshBasicMaterial
  var material = new THREE.MeshLambertMaterial({
    // color: 0x00ffff,
    map:texture,//设置地球0颜色贴图map
    // transparent:true,
    // opacity:0.5,//半透明效果
  }); 
  var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
  return mesh
}


//加载一个obj
const xiaoxiong=new OBJLoader()

xiaoxiong.load(
	// resource URL
	'小白熊.obj',
	// called when resource is loaded
	function ( object ) {
    object.position.x=10
    object.position.y=50
    object.position.z=108
    object.scale.x=10
    object.scale.y=10
    object.scale.z=10
    object.lookAt(0,0,0);
    object.rotateOnAxis(new THREE.Vector3( 1, 0, 0 ), -Math.PI/2)
    object.rotateOnAxis(new THREE.Vector3( 0, 1, 0 ), -Math.PI)
    object.rotateOnAxis(new THREE.Vector3( 1, 0, 0 ), -Math.PI/4)
		earth.add( object );
  },
  
	// called when loading is in progresses
	function ( xhr ) {

		console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

	},
	// called when loading has errors
	function ( error ) {

		console.log( 'An error happened' );

	}
);


//画圓
// const c_geometry = new THREE.CircleGeometry( 5, 32,0,3.14 );
// const c_material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
// const c_circle = new THREE.Mesh( c_geometry,c_material );
// c_circle.rotateX(45);
// c_circle.rotation
// earth.add( c_circle );


//添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(200);
earth.add(axesHelper);

//移动小熊
// let p1={}
// p1.x=0;p1.y=0;p1.z=120;
// let p2={}
// p2.x=10;p2.y=0;p2.z=119.583;
// let p3=xyz2xyz(p1,p2,5,120,3);

// let 中点 = new THREE.Vector3( p2.x, p2.y,p2.z );
// const origin = new THREE.Vector3( 0, 0, 0 );
// 中点.normalize();
// let xarrowHelper1 = new THREE.ArrowHelper( 中点, origin, 130, 0xffeeee );
// earth.add(xarrowHelper1);

// let 终点 = new THREE.Vector3( p3.x, p3.y,p3.z );
// 终点.normalize();
// let xarrowHelper2 = new THREE.ArrowHelper( 终点, origin, 130, 0xff0000 );
// earth.add(xarrowHelper2);

// let LINE_COLOR= '#ffffff';

//画弧线
// let curve = new THREE.EllipseCurve(
//   0,
//   0, // ax, aY
//   R + 1,
//   R + 1, // xRadius, yRadius
//   (0 / 180) * Math.PI,
//   (40 / 180) * Math.PI, // aStartAngle, aEndAngle
//   false, // aClockwise
//   0 // aRotation
// );
// let points = curve.getPoints(32);
// let geometry = new THREE.BufferGeometry().setFromPoints(points);
// let material = new THREE.LineBasicMaterial({ color: LINE_COLOR });

// let ellipse = new THREE.Line(geometry, material);
// ellipse.rotation.z = (90 / 180) * Math.PI;
// earth.add(ellipse);

//initLines();

function rotateToPos(pos) {
      let vp = new THREE.Vector3(pos.x, pos.y, pos.z);
      let vz = new THREE.Vector3(0, 0, 1);
  
      let angle = vp.angleTo(vz);
      let obj3d = new THREE.Object3D();
      let axis = vp.clone().cross(vz).normalize();
      if (axis.length() === 0) {
        axis.y = 1;
      }
      console.log('-------------', vp, vz, axis, (angle * 180) / Math.PI);
      obj3d.rotateOnAxis(axis, angle);
  
      let currentPos = {
        y: earth.rotation.y,
        z: earth.rotation.z,
        x: earth.rotation.x,
      };
      new TWEEN.Tween(currentPos)
        .to(
          {
            x: obj3d.rotation.x,
            y: obj3d.rotation.y,
            z: obj3d.rotation.z,
          },
          2000
        )
        .easing(TWEEN.Easing.Quadratic.Out)
        .onUpdate(()=>{
          updateTween(currentPos);
        })
        .start();
      obj3d = null;
    }

function updateTween(currentPos) {
      earth.rotation.x = currentPos.x;
      earth.rotation.y = currentPos.y;
      earth.rotation.z = currentPos.z;
}
  

function initLines() {
    // 经线
    let curve = new THREE.EllipseCurve(
      0,
      0, // ax, aY
      R + 1,
      R + 1, // xRadius, yRadius
      (63 / 180) * Math.PI,
      (-63 / 180) * Math.PI, // aStartAngle, aEndAngle
      true, // aClockwise
      0 // aRotation
    );
    let points = curve.getPoints(32);
    let geometry = new THREE.BufferGeometry().setFromPoints(points);
    let material = new THREE.LineBasicMaterial({ color: LINE_COLOR });

    for (let i = 0; i < 24; i++) {
      // Create the final object to add to the scene
      let ellipse = new THREE.Line(geometry, material);
      ellipse.rotation.y = ((5 + i * 15) / 180) * Math.PI;
      earth.add(ellipse);
    }
    // 纬线
    let angle_h = [63, 57, 50, 42, 33, 23, 12, 0, -12, -23, -33, -42, -50, -57, -63];
    angle_h.forEach((angle) => {
      let curve2 = new THREE.EllipseCurve(
        0,
        0, // ax, aY
        (R + 1 + Math.abs(angle / 40)) * Math.cos((angle / 180) * Math.PI),
        (R + 1 + Math.abs(angle / 40)) * Math.cos((angle / 180) * Math.PI), // xRadius, yRadius
        0,
        2 * Math.PI, // aStartAngle, aEndAngle
        true, // aClockwise
        0 // aRotation
      );
      let points2 = curve2.getPoints(64);
      let geometry2 = new THREE.BufferGeometry().setFromPoints(points2);
      let ellipse2 = new THREE.Line(geometry2, material);
      ellipse2.position.y = R * Math.sin((angle / 180) * Math.PI);
      ellipse2.rotation.x = 0.5 * Math.PI;
      earth.add(ellipse2);
    });
  }

export { earth,rotateToPos }